<script setup>
import {ref, computed, watch} from 'vue'

let orgStaffs = [
  {id: 1, name: '马冬梅', age: 18, sex: '女'},
  {id: 2, name: '周冬鲁', age: 20, sex: '女'},
  {id: 3, name: '周杰人', age: 21, sex: '男'},
  {id: 4, name: '温长人', age: 24, sex: '男'},
  {id: 5, name: '冬不拉', age: 33, sex: '女'},
  {id: 6, name: '人不周', age: 47, sex: '男'}
]

let staffs = computed(()=>{
  return orgStaffs.filter((item) => item.name.indexOf(searchText.value) >= 0)
})

let searchText = ref('')
let isDropdown = ref(false)
let selectedId = ref('')
let selectIdx  = ref(-1)
let searchlist = ref(null) //指向ref="searchlist"所在组件

function onEnterInput(){
  isDropdown.value = true
}

function onLeaveInput() {
  //使用timer延迟触发,让li标签的click事件先执行
  setTimeout(() => {
    isDropdown.value = false
  }, 200)
}

function searchClick() {
  isDropdown.value = true
}

function searchChange() {
  selectedId.value = ''
  selectIdx.value  = -1
}

function selectStaff(item, index) {
  selectedId.value = item.id
  searchText.value = item.name
  selectIdx.value  = index
  isDropdown.value = false
}

function selItemByKey(event) {
  if (event.key === 'ArrowDown'){
    if (selectIdx.value +1 < staffs.value.length) {
      selectIdx.value++
      selectedId.value = staffs.value[selectIdx.value].id
    }
  }else if (event.key === 'ArrowUp'){
    if (selectIdx.value > 0 && staffs.value.length > 0) {
      selectIdx.value--
      selectedId.value = staffs.value[selectIdx.value].id
    }
  }else if (event.key === 'Enter'){
    if (selectIdx.value >= 0 && selectIdx.value < staffs.value.length){
      searchText.value = staffs.value[selectIdx.value].name
      isDropdown.value = false
    }
  }
}

</script>

<template>
  <h3>列表搜索演示 (仿常用搜索框 - 用计算属性(computed)实现)</h3>

  <div class="container">
    <input
      placeholder="请输入要查找的名字"
      v-model="searchText"
      @focus="onEnterInput"
      @blur="onLeaveInput"
      @keydown="selItemByKey"
      @click="searchClick"
      @input="searchChange">
    <br>
    <ul ref="searchlist" v-show="isDropdown" class="searchbox">
      <li v-for="(item, index) in staffs"
          :key="item.id"
          @click="selectStaff(item, index)"
          class="searchitem"
          :class="{active: selectedId === item.id}">
        {{item.name}} - {{item.age}} - {{item.sex}}
      </li>
    </ul>
  </div>


</template>

<style scoped>

input {
  width: 296px;
}

.container {
  width: 300px;
}

.searchbox {
  margin: 3px 1px 2px 1px;
  padding: 0;
  width: 100%;
  border-radius: 5px;
  border: 2px solid skyblue;
}

.searchitem {
  list-style-type: none;
  padding-left: 5px;
}

.searchitem:hover {
  background-color: #e9abf5;
  color: navy;
  font-weight: bold;
  cursor: pointer;
}

.active {
  background-color: #d4e4f6;
}

</style>